<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button
            type="primary"
            @click="openAddRole"
          >添加角色</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="rolesList"
        border
        stripe
        style="width:100%;"
      >
        <!-- 展开行 -->
        <el-table-column type="expand">
          <template slot-scope="s">
            <!-- <pre>{{s.row}}</pre> -->
            <el-row
              v-for="(item,index) in s.row.children"
              :class="['border-bot' ,index==0?'border-top':'','center-flex']"
              :key="item.id"
            >
              <!-- 一级 -->
              <el-col :span="5">
                <el-tag
                  type="primary"
                  closable
                  @close="removeRoleByID(s.row,item.id)"
                >{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2,index2) in item.children"
                  :key="item2.id"
                  :class="[index2===0?'':'border-top','center-flex']"
                >
                  <el-col :span='6'>
                    <el-tag
                      type='success'
                      closable
                      @close="removeRoleByID(s.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span='18'>
                    <el-tag
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRoleByID(s.row,item3.id)"
                    >{{item3.authName}}
                      <!-- <pre>{{s.row}}</pre> -->
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 下标行 -->
        <el-table-column
          type="index"
          label="#"
        ></el-table-column>
        <el-table-column
          label="角色名称"
          prop="roleName"
        ></el-table-column>
        <el-table-column
          label="角色描述"
          prop="roleDesc"
        ></el-table-column>
        <el-table-column
          label="操作"
          width="300px"
        >
          <template slot-scope="s">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="openEdit(s.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delRole(s.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="openSetDialog(s.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="addDialogVisible"
      width="30%"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="80px"
      >
        <el-form-item
          label="角色名称"
          prop="rolename"
        >
          <el-input
            v-model="addForm.rolename"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
        >
          <el-input
            v-model="addForm.roleDesc"
            placeholder="请输入角色描述（选填项）"
          ></el-input>
        </el-form-item>
      </el-form>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addRole"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="editDialogVisible"
      width="30%"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        label-width="80px"
        :rules="editFormRules"
      >
        <el-form-item
          label="角色名称"
          prop="roleName"
        >
          <el-input
            v-model="editForm.roleName"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
        >
          <el-input
            v-model="editForm.roleDesc"
            placeholder="请输入角色描述（选填项）"
          ></el-input>
        </el-form-item>
      </el-form>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="editRole"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="setDialogVisible"
      width="30%"
      @close='setDialogClose'
    >
      <el-tree
        ref="treeRef"
        :data="rightsList"
        :props="rightsListProps"
        show-checkbox
        :default-expand-all='true'
        node-key='id'
        :default-checked-keys='defaultRightsList'
      ></el-tree>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="ensureAllotRights"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 添加角色弹出框
      addDialogVisible: false,
      editDialogVisible: false,
      setDialogVisible: false,
      // 添加用户表单
      addForm: {
        rolename: '',
        roleDesc: '',
      },
      editForm: {
        id: 0,
        rolename: '',
        roleDesc: '',
      },
      editFormRules: {
        roleName: [
          { required: true, message: '请输入用户名！', trigger: 'blur' },
          {
            min: 1,
            max: 13,
            message: '长度在 1 到 13 个字符',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          { required: false, message: '请输入描述（可不填）', trigger: 'blur' },
          {
            min: 1,
            max: 13,
            message: '长度在 1 到 13 个字符',
            trigger: 'blur',
          },
        ],
      },
      rightsList: [],
      // el-tree绑定的对象
      rightsListProps: {
        children: 'children',
        label: 'authName',
      },
      // 角色拥有的权限列表
      defaultRightsList: [],
      // 打开分配权限对话框，传入选中的角色ID值
      selectedRoleID: 0,
    }
  },
  methods: {
    async getRolesList() {
      var { data: result } = await this.$axios.get('roles')
      // console.log(result)
      if (result.meta.status == 200) {
        this.rolesList = result.data
      } else {
        this.$message.error(result.meta.msg)
      }
    },
    openAddRole() {
      this.addDialogVisible = true
    },
    async addRole() {
      var { data: result } = await this.$axios.post('roles', {
        roleName: this.addForm.rolename,
        roleDesc: this.addForm.roleDesc,
      })
      console.log(result)
      if (result.meta.status == 201) {
        this.$message.success(result.meta.msg)
        this.getRolesList()
        this.addDialogVisible = false
      } else {
        this.$message.error(result.meta.msg)
      }
    },
    async delRole(id) {
      var result = await this.$confirm(
        '此操作将会永久删除该用户，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((e) => {
        return e
      })
      console.log(result)
      if (result === 'confirm') {
        var { data: result2 } = await this.$axios.delete(`roles/${id}`)
        // console.log(result2);
        if (result2.meta.status == 200) {
          this.getRolesList()
          this.$message.success(result2.meta.msg)
        } else {
          this.$message.error(result2.meta.msg)
        }
      } else {
      }
    },
    // 获取该条编辑的角色
    async openEdit(id) {
      this.editDialogVisible = true
      // 先获取数据，然后才能编辑
      var { data: result } = await this.$axios.get(`roles/${id}`)
      // console.log(result)
      if (result.meta.status == 200) {
        this.editForm = result.data
      } else {
        this.$message.error(result.meta.msg)
      }
    },
    // 确认修改
    async editRole() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('不合法的值')
        // 验证通过 id值在打开窗口按钮时候就通过form表单传过去了
        // 表单提交总是有错误 所以打印表单
        console.log(this.editForm)
        var { data: result } = await this.$axios.put(
          `roles/${this.editForm.roleId}`,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc,
          }
        )
        // console.log(result,275);
        if (result.meta.status == 200) {
          // 修改成功
          this.editDialogVisible = false
          this.$message.success('修改成功')
          this.getRolesList()
        } else {
          this.$message.error(result.meta.msg)
        }
      })
    },
    // 重置修改用户对话框验证提示信息
    resetEditForm() {
      this.$refs.editFormRef.resetFields()
    },
    // 移除角色的三级权限
    async removeRoleByID(role, rightID) {
      var result = await this.$confirm(
        '此操作将会删除该权限，是否继续',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((e) => {
        return e
      })
      // console.log(result)
      if (result === 'confirm') {
        // 确认删除
        var { data: result2 } = await this.$axios.delete(
          `roles/${role.id}/rights/${rightID}`
        )
        console.log(result2)
        if (result2.meta.status == 200) {
          this.$message.success('删除权限成功！')
          // 会导致页面重新渲染 不推荐使用
          // this.getRolesList()
          role.children = result2.data
        } else {
          this.$message.error('删除失败！')
        }
      } else {
        this.$message.info('取消了删除')
      }
    },
    // 打开分配用户权限对话框
    async openSetDialog(role) {
      // console.log(role);
      // 选中的角色ID
      this.selectedRoleID = role.id
      // var {data:result2}=await this.$axios.get('rights/list')
      var { data: result } = await this.$axios.get('rights/tree')
      // console.log(result2,'list');
      // console.log(result,'tree');
      // 把页面对话框的权限重新赋值
      this.rightsList = result.data
      // console.log(role);
      // 递归找到所有的三级权限
      this.getLeafRights(role, this.defaultRightsList)
      this.setDialogVisible = true
    },
    // 找到此角色拥有的所有的三级权限
    getLeafRights(node, arr) {
      if (!node.children) {
        // 是三级节点 注意是push ID值
        return arr.push(node.id)
      } else {
        // 不是三级节点
        // 错误的写法
        // this.getLeafRights(node.children, arr)
        node.children.forEach((item) => {
          return this.getLeafRights(item, arr)
        })
      }
    },
    setDialogClose() {
      this.defaultRightsList = []
    },
    // 确认分配权限
    async ensureAllotRights() {
      var keys = []
      // 错误的写法
      // var result = this.treeRef.getHalfCheckedKeys()
      // 半选中的节点
      var result = this.$refs.treeRef.getHalfCheckedKeys()
      // console.log(result)
      var result2 = this.$refs.treeRef.getCheckedKeys()
      // console.log(result2)
      keys = [...result, ...result2]
      console.log(keys)
      var keysStr = keys.join(',')
      console.log(keysStr)
      var { data: result3 } = await this.$axios.post(
        `roles/${this.selectedRoleID}/rights`,
        {
          rids: keysStr,
        }
      )
      console.log(result3)
      if (result3.meta.status == 200) {
        this.$message.success(result3.meta.msg)
        this.setDialogVisible = false
this.getRolesList()
      } else {
        this.$message.error(result3.meta.msg)
      }
    },
  },
  created() {
    this.getRolesList()
  },
}
</script>
<style lang="less" scoped>
@border:1px solid #ddd;
.el-tag {
  margin: 7px;
}
.border-bot {
  border-bottom: @border;
}
.border-top {
  border-top: @border;
}
.center-flex {
  display: flex;
  align-items: center;
}
</style>
